import { Controller, Get, Req, Param, Query } from '@nestjs/common';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
var nodemailer = require('nodemailer');
@ApiTags("验证码")
@Controller('code')
export class CodeController {

    @Get("CreateCode/:email")
    async CreateCode(@Req() req,@Param("email") email:string){
        
        var code=this.genCode(6)
        req.session['code']=code

        var mailTransport = nodemailer.createTransport({
            host : 'smtp.qq.com',
            secureConnection: true, // 使用SSL方式（安全方式，防止被窃取信息）
            auth : {
              user : '1250459446@qq.com',
              pass : 'qhyewtbvxmvljaec'
            },
        });
        var options = {
            from:"1250459446@qq.com",
            to:email,
            // cc     : ''  //抄送
            // bcc     : ''  //密送
            subject: '论文系统注册验证码',
            text: '验证码:'+code,
     
        };
        const res=mailTransport.sendMail(options);
        return{
            statucode:200,
            code:res
        }
    }


    @Get("CheckCode/:code")
    CheckCode(@Param("code") code:string,@Req() req){
        
        
        var acode=String(req.session.code).toLowerCase()==String(code).toLowerCase()
        return{
            statucode:200,
            isSame:acode,
            CODE:String(req.session.code)
        }
    }







    genCode (len):string {
        if (typeof len === "undefined") // 默认验证码长度为4
        len = 4;
        // 生成 48 ~ 122 之间的随机整数
        // 0 ~ 74
        var validateCode = "";


        while (validateCode.length < len) {
           var rand = Math.floor(Math.random() * 75) + 48;
           // console.log(rand);
           // 判断是否在数字、大/小写字符范围内
           if (rand >= 48 && rand <= 57
           || rand >= 65 && rand <= 90
           || rand >= 97 && rand <= 122) {
              validateCode += String.fromCharCode(rand);
           }
        }


        return validateCode;
    }

}
